import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { getEnvInfo } from '@/api/getEnvironment.js'
import {getHistoryData} from '@/api/getHistoryData.js'
import {computed} from "vue";
import {useStore} from "vuex";
export const useWebSocketStore = defineStore('websocket', () => {
    const socket = ref<WebSocket | null>(null)
    // 1. 直接定义类型和默认值合二为一
    /**
     * 创建策略数据对象，包含各种电力相关指标和状态数据
     * @returns 策略数据对象
     */
    const createStrategyData = () => ({
        hours: [] as string[],           // 时间标签数据，记录各时间点
        electricityCost: [] as number[], // 电费数据，各时间点的电费金额
        powerConsumption: [] as number[], // 总发电量数据，各时间点的总发电量
        unitPrice: [] as number[],       // 单位电价数据，各时间点的电价
        batteryEnergy: [] as number[],   // 电池剩余电量数据，各时间点电池剩余电量
        chargeStatus: [] as number[],    // 充放电状态数据，各时间点电池充放电状态
        gridPower: [] as number[],       // 国网电量花费，各时间点从电网购电的电量
        solarPower: [] as number[],      // 太阳能用电量数据，各时间点太阳能发电使用量
        windPower: [] as number[],       // 风能用电量数据，各时间点风能发电使用量
        batteryPower: [] as number[],    // 电池用电量数据，各时间点电池放电量
        totalSolarPower: 0,              // 总太阳能用电量数据，统计周期内太阳能总使用量
        totalWindPower: 0,               // 总风能用电量数据，统计周期内风能总使用量
        totalGridPower: 0,               // 总网电用电量数据，统计周期内从电网购电总量
        totalBatteryPower: 0,            // 总电池用电量数据，统计周期内电池放电总量
        totalEmission: 0,                // 总排放数据，统计周期内的碳排放总量
    } as const);

// 2. 直接从工厂函数推断出类型
//     type StrategyData = ReturnType<typeof createStrategyData>;
    const cdata = reactive({
        actualLoad:[],  // 实际负荷数据
        simple:createStrategyData(),
        a2c:createStrategyData(),
        dqn:createStrategyData(),
        ppo:createStrategyData()
    })
    const isConnected = ref(false)
    const totalEnergy = ref()
    const envParam = ref()
    const totalConsumption = ref(0)
    const store = useStore()
    const envParamId = computed(() => store.getters.getEnvParamId) // 策略列表
    const getTotalEnergyAndActualLoad = async () => {
        try{
            const res = await getEnvInfo(envParamId.value)
            console.log("仿真参数数据", res.data)
            totalEnergy.value = res.data.data.battery.capacity
            const parameters = res.data.data?.parameters || []
            const targetItem = parameters.find(item => item.category_id === 5)
            const targetValueList = targetItem?.value_list || []
            cdata.actualLoad = targetValueList
            totalConsumption.value = targetValueList
                .filter(num => typeof num === 'number' && !isNaN(num))
                .reduce((sum, current) => sum + current, 0)
            envParam.value = res.data.data.parameters
            console.log("环境参数数据", envParam.value)
            console.log("总用电量", totalConsumption.value)
        }
        catch(error){
            console.log(error)
        }
    }

    const connectWebSocket = (envParamId : string, simulationResultTotalId : string) => {
        try {
            if (isConnected.value) return // 避免重复连接

            // 清空数据
            // 清空 simple 对象中的所有数组
            cdata.simple = createStrategyData()

            // 清空 a2c 对象中的所有数组
            cdata.a2c = createStrategyData()

            // 清空 dqn 对象中的所有数组
            cdata.dqn = createStrategyData()

            // 清空 ppo 对象中的所有数组
            cdata.ppo = createStrategyData()

            socket.value = new WebSocket(
                `ws://localhost:8081/simulation/start_simulation?env_param_id=${envParamId}&simulation_id=${simulationResultTotalId}`
            )
            socket.value.onopen = () => {
                isConnected.value = true
            }
            socket.value.onmessage = (event) => {
                if (!isConnected.value) return  // 添加状态检查
                try {
                    const data = JSON.parse(event.data)
                    const type = data.simulation_type;
                    const sim = data.simulation_result;

                    //动态访问对应的数据存储对象
                    const targetData = cdata[type]
                    // targetData.isLoading = false;
                    store.commit('SET_STRATEGY_LOADING', { value: type, isLoading: false })
                    // 处理时间标签
                    const timeLabel = sim.time_point
                        ? new Date(sim.time_point).toLocaleTimeString()
                        : `Hour ${targetData.hours.length + 1}`
                    // 填充数据到cdata（根据后端实际字段调整）
                    targetData.hours.push(timeLabel)
                    targetData.solarPower.push(Number(sim.solar_power))
                    targetData.windPower.push(Number(sim.wind_power))
                    targetData.gridPower.push(Number(sim.grid_power))
                    targetData.totalSolarPower = (Number(targetData.totalSolarPower)) + Number(sim.solar_power);
                    targetData.totalWindPower = (Number(targetData.totalWindPower)) + Number(sim.wind_power);
                    targetData.totalGridPower = (Number(targetData.totalGridPower)) + Number(sim.grid_power);
                    targetData.totalEmission = (Number(targetData.totalEmission)) + Number(sim.grid_emission)
                    +Number(sim.solar_emission)+Number(sim.wind_emission);
                    targetData.electricityCost.push(Number(sim.grid_cost + sim.solar_cost + sim.wind_cost))
                    const prevEnergy = targetData.batteryEnergy.length > 0
                        ? (targetData.batteryEnergy[targetData.batteryEnergy.length - 1] * totalEnergy.value / 100)
                        : null;
                    const energyPercentage = (sim.battery_energy / totalEnergy.value) * 100;
                    if (prevEnergy == null)
                        targetData.chargeStatus.push(0)
                    else {
                        targetData.chargeStatus.push(sim.battery_energy - prevEnergy)
                        if (sim.battery_energy - prevEnergy < 0) {
                            targetData.batteryPower.push(prevEnergy - sim.battery_energy)
                            targetData.totalBatteryPower = (Number(targetData.totalBatteryPower)) + Number(prevEnergy - sim.battery_energy);
                        } else {
                            targetData.batteryPower.push(0)
                        }//如果电池放电，说明这个是对外供电，也在发电
                    }  //电池充电则为正，放电则为负
                    targetData.batteryEnergy.push(energyPercentage)  //剩余电量百分比
                    if (sim.batteryEnergy - prevEnergy > 0) {  //电池充电，实际发电量需要减去这个充电量
                        targetData.powerConsumption.push(Number(sim.grid_power + sim.solar_power + sim.wind_power
                            - (sim.battery_energy - prevEnergy)))
                    } else {
                        targetData.powerConsumption.push(Number(sim.grid_power + sim.solar_power + sim.wind_power
                        +  (prevEnergy - sim.battery_energy)))
                    }
                    // 计算单位电价（排除功率为0的项）
                    const prices = [];
                    // 检查电网功率和成本，非0时加入计算
                    if (sim.grid_power && sim.grid_cost) {
                        const gridPrice = Number(sim.grid_cost) / Number(sim.grid_power);
                        prices.push(gridPrice);
                    }
                    // 检查太阳能功率和成本，非0时加入计算
                    if (sim.solar_power && sim.solar_cost) {
                        const solarPrice = Number(sim.solar_cost) / Number(sim.solar_power);
                        prices.push(solarPrice);
                    }
                    // 检查风能功率和成本，非0时加入计算
                    if (sim.wind_power && sim.wind_cost) {
                        const windPrice = Number(sim.wind_cost) / Number(sim.wind_power);
                        prices.push(windPrice);
                    }
                    // 计算有效项的平均值（若无有效项则为0）
                    const unitPrice = prices.length > 0
                        ? prices.reduce((sum, price) => sum + price, 0) / prices.length
                        : 0;
                    // 存入cdata
                    targetData.unitPrice.push(Number(unitPrice.toFixed(2))); // 保留两位小数
                } catch (e) {
                    console.error('解析WebSocket数据失败:', e)
                }
            }
        }
        catch (e) {
            console.error('连接WebSocket失败:', e)
        }
    }


    const historyData = (simulationId :string)=>{
         getHistoryData(simulationId).then(res=>{
             console.log("历史数据",res.data)
             console.log("totalCapacity",totalEnergy.value)
             console.log("envParamId",envParamId.value)
             let historyData : any[] = [];
             historyData = res.data.data.results
             historyData.forEach((item, index) => {
                 const targetData = cdata[item.strategy]
                 const resultMaps = item.result_maps
                 resultMaps.forEach((resultData,index)=>{
                     const sim = resultData.simulation_result;
                     const batteryEnergy = Number(sim.battery_energy);
                     const time = sim.time_point
                     const solarPower = Number(sim.solar_power);
                     const windPower = Number(sim.wind_power);
                     const gridPower = Number(sim.grid_power);
                     const solarCost = Number(sim.solar_cost);
                     const windCost = Number(sim.wind_cost);
                     const gridCost = Number(sim.grid_cost);
                     const solarEmission = Number(sim.solar_emission);
                     const windEmission = Number(sim.wind_emission);
                     const gridEmission = Number(sim.grid_emission);
                     const timeLabel = time
                         ? new Date(time).toLocaleTimeString()
                         : `Hour ${targetData.hours.length + 1}`
                     // 填充数据到cdata（根据后端实际字段调整）
                     targetData.hours.push(timeLabel);
                     targetData.solarPower.push(Number(solarPower))
                     targetData.windPower.push(Number(windPower))
                     targetData.gridPower.push(Number(gridPower))
                     targetData.totalSolarPower = (Number(targetData.totalSolarPower)) + Number(solarPower);
                     targetData.totalWindPower = (Number(targetData.totalWindPower)) + Number(windPower);
                     targetData.totalGridPower = (Number(targetData.totalGridPower)) + Number(gridPower);
                     targetData.totalEmission = (Number(targetData.totalEmission)) + Number(gridEmission)
                         +Number(solarEmission)+Number(windEmission);
                     targetData.electricityCost.push(Number(gridCost + solarCost + windCost))
                     const prevEnergy = targetData.batteryEnergy.length > 0
                         ? (targetData.batteryEnergy[targetData.batteryEnergy.length - 1] * totalEnergy.value / 100)
                         : null;
                     const energyPercentage = (batteryEnergy / totalEnergy.value) * 100;
                     if (prevEnergy == null)
                         targetData.chargeStatus.push(0)
                     else {
                         targetData.chargeStatus.push(batteryEnergy - prevEnergy)
                         if (batteryEnergy - prevEnergy < 0) {
                             targetData.batteryPower.push(prevEnergy - batteryEnergy)
                             targetData.totalBatteryPower = (Number(targetData.totalBatteryPower)) + Number(prevEnergy - batteryEnergy);
                         } else {
                             targetData.batteryPower.push(0)
                         }//如果电池放电，说明这个是对外供电，也在发电
                     }  //电池充电则为正，放电则为负
                     targetData.batteryEnergy.push(energyPercentage)  //剩余电量百分比
                     if (batteryEnergy - prevEnergy > 0) {  //电池充电，实际发电量需要减去这个充电量
                         targetData.powerConsumption.push(Number(gridPower + solarPower + windPower
                             - (batteryEnergy - prevEnergy)))
                     } else {
                         targetData.powerConsumption.push(Number(gridPower + solarPower + windPower
                             +  (prevEnergy - batteryEnergy)))
                     }
                     // 计算单位电价（排除功率为0的项）
                     const prices = [];
                     // 检查电网功率和成本，非0时加入计算
                     if (gridPower && gridCost) {
                         const gridPrice = Number(gridCost) / Number(gridPower);
                         prices.push(gridPrice);
                     }
                     // 检查太阳能功率和成本，非0时加入计算
                     if (solarPower && solarCost) {
                         const solarPrice = Number(solarCost) / Number(solarPower);
                         prices.push(solarPrice);
                     }
                     // 检查风能功率和成本，非0时加入计算
                     if (windPower && windCost) {
                         const windPrice = Number(windCost) / Number(windPower);
                         prices.push(windPrice);
                     }
                     // 计算有效项的平均值（若无有效项则为0）
                     const unitPrice = prices.length > 0
                         ? prices.reduce((sum, price) => sum + price, 0) / prices.length
                         : 0;
                     // 存入cdata
                     targetData.unitPrice.push(Number(unitPrice.toFixed(2))); // 保留两位小数
                 })
             });
             console.log("历史数据cdata",cdata)
         }
     ).catch(error=>{
         console.log(error)
     })
    }
    const closeWebSocket = () => {
        socket.value?.close()
        isConnected.value = false
    }

    return { cdata,totalEnergy, connectWebSocket, closeWebSocket, getTotalEnergyAndActualLoad,envParam,totalConsumption,historyData }
})